package util;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Properties;

import common.Constants;

import crawler.CrawlerDocument;
import crawler.DocumentPool;

import junit.framework.Assert;
import junit.framework.TestCase;

public class FileLoaderTest extends TestCase {

	protected void setUp() throws Exception {
		super.setUp();
	}

	protected void tearDown() throws Exception {
		super.tearDown();
	}

	public final void testLoadSimpleList() throws IOException {
		
		ArrayList<String> list = null;
		
		list = FileLoader.LoadSimpleList("data/util.FileLoader.LoadSimpleList.test");
		
		Assert.assertEquals(2, list.size());
		Assert.assertEquals("line1", list.get(0));
		Assert.assertEquals("line2 line 2", list.get(1));
	}
	
	public final void testLoadContent() throws IOException{
		String expected = "Hello\r\nWorld\r\n\r\n";
		String actual = FileLoader.LoadContent("data/util.FileLoader.LoadContent.test");
		Assert.assertEquals(expected, actual);
	}

	public final void testLoadSeed() throws InterruptedException, IOException {
		
		ArrayList<CrawlerDocument> seedlist = FileLoader.LoadSeed("data/util.FileLoader.LoadSeed.test");
		
		Assert.assertEquals(2, seedlist.size());
		
		CrawlerDocument doc = null;
		String url = null;
		String xpath_root = null;
		HashMap<String, String> xpaths = null;
		
		doc = seedlist.get(0);
		url = doc.getUrlStr();
		xpath_root = (String)doc.getFeature(Constants.DOC_FEATURE_KEY_XPATH_ROOT); 
		xpaths = (HashMap<String, String>)doc.getFeature(Constants.DOC_FEATURE_KEY_XPATHS);		
		String title = xpaths.get("title");
		String image = xpaths.get("image");
		
		Assert.assertEquals("http://lashou.com", url);
		Assert.assertEquals("root/level1/", xpath_root);
		Assert.assertEquals("data/title", title);
		Assert.assertEquals("image", image);
			
		doc = seedlist.get(1);
		url = doc.getUrlStr();
		xpath_root = (String)doc.getFeature(Constants.DOC_FEATURE_KEY_XPATH_ROOT); 
		xpaths = (HashMap<String, String>)doc.getFeature(Constants.DOC_FEATURE_KEY_XPATHS);
		String start = xpaths.get("start");
		String end = xpaths.get("end");
		
		Assert.assertEquals("http://meituan.com", url);
		Assert.assertEquals("meituan/root/", xpath_root);
		Assert.assertEquals("data/startTime", start);
		Assert.assertEquals("data/endTime", end);
	}
	
	public final void testLoadProperties(){
		Properties config = null;
		try {
			config = FileLoader.LoadProperties("data/util.FileLoader.LoadProperties.test");
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		String expected = "value1";
		String actual = config.getProperty("key1");		
		Assert.assertEquals(expected, actual);
		
		expected = "value2";
		actual = config.getProperty("key2");
		Assert.assertEquals(expected, actual);
	}

}
